package com.fla.live.im;

import com.fla.aiba.entity.live.LiveRoom;

import com.fla.live.im.handler.ChatRoomAttr;
import com.fla.live.im.handler.ChatRoomHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 全局用户管理器
 * @author Administrator
 *
 */
public class RoomManage {
	
	
 private static final Logger log= LoggerFactory.getLogger(RoomManage.class);
 private static class ChatRoomManageHolder {  
      private static final RoomManage INSTANCE = new RoomManage();
  }  
 
  private RoomManage(){}
  
  public  static RoomManage getInstance(){
  		return ChatRoomManageHolder.INSTANCE;
     
  }
  
  private static Map<Long,LiveRoom> liveRooms=new ConcurrentHashMap<>();
  /**
   * 为每个放间分配一个key来管理在线用户
   * 所有连接的用户
   */
  private static  Map<Long,Map<String,ChannelHandlerContext>> roomMember=new ConcurrentHashMap<>();
  
  
    /**
     * 添加用户
     * @param roomId
     * @param userId
     * @param ctx
     */
   public void add(Long roomId,String userId, ChannelHandlerContext ctx){
	   
	   try {
			Map<String,ChannelHandlerContext> room=roomMember.get(roomId);
			if(room==null){
				room=new ConcurrentHashMap<>();
			}
			 room.putIfAbsent(userId, ctx);
		  	 roomMember.put(roomId, room);
			log.info("房间["+roomId+"],新增用户["+userId+"].当前房间在线人数"+room.size());
		} catch (Exception e) {
			log.error("添加用户失败[{}]",e.getMessage());
		
		}
	
	}
	
   /**
    * 清除掉线的用户
    * @param ctx
    */
   public void remove(ChannelHandlerContext ctx){
	   Attribute<ChatRoomAttr> attr = ctx.attr(ChatRoomHandler.CHAT_ROOM_ATTR);
	   ChatRoomAttr roomAttr=attr.get();
	   if(roomAttr!=null){
		   Map<String,ChannelHandlerContext> room= roomMember.get(roomAttr.getRoomId());
		   room.remove(roomAttr.getUserId(),ctx);
		   log.debug("用户退出["+roomAttr.getUserId()+"]房间["+roomAttr.getRoomId()+"],当前在线人数"+room.size());
		   attr.remove();
		}
	}
   /**
    * 移除掉线的用户
    * @param roomId
    * @param userId
    * @param ctx
    * @throws Exception
    */
	@SuppressWarnings("null")
	public void remove(Long roomId,String userId,ChannelHandlerContext ctx){
		
		Map<String,ChannelHandlerContext> room=roomMember.get(roomId);
		try {
			if(room==null){
				room.remove(userId, ctx);
				System.out.println("user loginout...["+userId+"]");
				System.out.println("now user size...["+room.size()+"]");
			}
				
			if(room.size()==0){//回收空间
				roomMember.remove(room);
				System.out.println("房间称除");
			}	
				
		} catch (Exception e) {
			System.err.println("reomve user error :"+e.getMessage());
		}
		
	}
	
	/**
	 *  指定房间广播消息
	 * @param roomId

	 * @param msg
	 */
	public void broadcastRoom(Long roomId,Object msg,String ... users){
		
			Map<String,ChannelHandlerContext> room=roomMember.get(roomId);
			  for(String userId:room.keySet()){
				  if(checkUser(userId, users))
					  continue;
				  try {
					  room.get(userId).writeAndFlush(msg);
					} catch (Exception e) {
						System.out.println("发送失败。。。"+e.getMessage());
					}
				   
			 }
		
	}	
	
	
	/**
	 * 全房间广播

	 */
	public void broadcastALL(Object msg){
		     for (Map<String,ChannelHandlerContext> room : roomMember.values()) {
		    	 for(String userId:room.keySet()){
					  try {
						  room.get(userId).writeAndFlush(msg);
					} catch (Exception e) {
						log.error("消息发送失败，"+e.getMessage());
					}
		    	  }
		     }
			
		
}	
	
	private Boolean checkUser(String userId,String ...users){
		for(String u:users){
	  		if(u.equals(userId))
	  			return true;
	    }
		return false;
	}


	public void addRoom(LiveRoom room){
		this.liveRooms.put(room.getLive().getLiveId(),room);
	}
	public List<LiveRoom> getRooms(){
		List<LiveRoom> arrayRooms=new ArrayList<>();
		for (Long liveId:liveRooms.keySet()) {
			arrayRooms.add(liveRooms.get(liveId));
		}
		return arrayRooms;
	}
	public LiveRoom getRoom(Integer liveId){
		return liveRooms.get(liveId);
	}
	public void roomRoom(Integer liveId){
		 liveRooms.remove(liveId);
	}
}
